/* eslint-disable @typescript-eslint/no-object-literal-type-assertion */
//@ts-ignore
import getMessage from 'ts-msg-handler'
import { mallApi } from '/api/mall'
import { getUser } from '/store/actions'
import { checkUserisVip, getAppId, getServer } from '/store/mutations'
import { GlobalData } from '/store/state'
import { $event } from '/utils'

Page({
  data: {
    top: GlobalData.menuRect.top,
    height: GlobalData.menuRect.height,
    orderInfo: {} as any,
    orderInfoTemp: {} as any, // 当前点击的订单数据。如果是单个订单则和orderInfo同。如果是聚合订单则为子订单数据
    orderId: 0,
    orderIds: [] as Array<any>,
    scrollTop: false,
    id: 0, //4销售,5兑换
    isSaleOrder: false, // 是否是销售订单
    currencyName: GlobalData.currencyName,
    can_comment: true,
    mall_commodities: {} as any,
    index: 0,
    user: {} as any,
    countPrice: 0,
    show: false,
    boxType: '',
  },
  async onLoad(options: any) {
    $event.on('after:mall_commodities', this, () => {
      const {
        data: { orderInfo },
      } = this
      orderInfo.comment_id = 1
      this.setData({ orderInfo })
    })
    $event.on('mallOrderChange', this, () => {
      this.fetchInfo()
    })
    this.setData({
      index: +options.index,
      id: +options.id,
      isSaleOrder: +options.id == 4,
      orderId: +options.orderId,
    })
    this.fetchInfo()
  },
  async fetchInfo() {
    const { id, isSaleOrder, orderId } = this.data
    const orderInfo = await mallApi.getMallOrder(orderId, {
      with: `user,shopkeeper,expresses.company,refund.expresses.company,refund.negotiates,apply,appeal`,
      sub_orders: 1,
      noGroupBy: 1,
    })
    /** 获取用户信息 */
    const user = getUser()
    if (user.vip) {
      user.vip.isVip = checkUserisVip(user)
    }
    let countPrice = 0

    /** 未支付订单
     *  0-待付款(PS_UNPAID)，1-已付款，但处理失败(PS_FAILED)，
     *  2-付款成功(PS_SUCCEEDED)，3-订单过期(PS_EXPIRED)，4-订单取消(PS_CANCEL)
     */
    if ([0, 3, 4].includes(+orderInfo.pay_status)) {
      /** 多条订单 */
      if (orderInfo.parentOrder) {
        orderInfo.sub_orders.forEach((i: any) => {
          i.forEach((j: any) => {
            /** 如果商品存在规格，则取规格价 */
            if (j.commodity.comcommodity_option) {
              j.commodity.commodity_option &&
                j.commodity.sku.forEach((item: any) => {
                  if (item.name === i.commodity.commodity_option) {
                    countPrice += (item.extra + j.commodity.market_price) * j.quantity
                  } else {
                    countPrice += j.commodity.market_price * j.quantity
                  }
                })
            } else {
              countPrice += j.commodity.market_price * j.quantity
            }
          })
        })
      } else {
        /**单条订单*/
        /** 如果商品存在规格，则取规格价 */
        if (orderInfo.commodity.comcommodity_option) {
          orderInfo.commodity.commodity_option &&
            orderInfo.commodity.sku.forEach((item: any) => {
              if (item.name === orderInfo.commodity.commodity_option) {
                countPrice += (item.extra + orderInfo.commodity.market_price) * orderInfo.quantity
              } else {
                countPrice += orderInfo.commodity.market_price * orderInfo.quantity
              }
            })
        } else {
          countPrice += orderInfo.commodity.market_price * orderInfo.quantity
        }
      }
    }

    // 状态
    if (orderInfo.parentOrder) {
      // 聚合订单，有子订单
      orderInfo.sub_orders.forEach((order: any) => {
        order.status_resolve = this.orderStatusResolve(order, isSaleOrder)
      })
    } else {
      orderInfo.status_resolve = this.orderStatusResolve(orderInfo, isSaleOrder)
    }
    // 订单已冻结 、申诉已受理 状态下不可操作
    if (orderInfo.locked != 1 && orderInfo.locked != 2) {
      if (orderInfo.parentOrder) {
        orderInfo.showDel = true
        // 聚合订单状态基本无用，需要通过子订单进行判断
        for (const order of orderInfo.sub_orders) {
          // 发货
          if (['PS_SUCCEEDED', 'RF_REFUSE'].includes(order.status)) {
            orderInfo.showWriteShip = true
          }
          // 收货
          if (['EP_SEND', 'RT_REFUSE'].includes(order.status)) {
            orderInfo.showConfirmShip = true
          }
          // 删除(需要所有子订单都满足能删除状态)
          if (
            !orderInfo.showDel ||
            ![
              'PS_EXPIRED',
              'PS_CANCEL',
              'EP_SIGNED',
              'EP_TIMEOUT',
              'RF_FINISH',
              'RT_FINISH',
              'RT_NEGO_FINISH',
              'CLOSE',
              'COMMENTED',
            ].includes(order.status)
          ) {
            orderInfo.showDel = false
          }
        }
      } else {
        // 发货
        if (['PS_SUCCEEDED', 'RF_REFUSE'].includes(orderInfo.status)) {
          orderInfo.showWriteShip = true
        }
        // 收货
        if (['EP_SEND', 'RT_REFUSE'].includes(orderInfo.status)) {
          orderInfo.showConfirmShip = true
        }
        // 删除
        if (
          [
            'PS_EXPIRED',
            'PS_CANCEL',
            'EP_SIGNED',
            'EP_TIMEOUT',
            'RF_FINISH',
            'RT_FINISH',
            'RT_NEGO_FINISH',
            'CLOSE',
            'COMMENTED',
          ].includes(orderInfo.status)
        ) {
          orderInfo.showDel = true
        }
      }
    }

    this.setData({
      countPrice,
      user,
      currencyName: GlobalData.currencyName,
      top: GlobalData.menuRect.top,
      height: GlobalData.menuRect.height,
      orderInfo,
      orderId: orderInfo.id,
      id: +id,
    })
  },
  // 查看物流
  logisticsDetail(e: WechatMiniprogram.CustomEvent) {
    const { order } = e.currentTarget.dataset

    // 多订单
    if (order.expresses.length > 1) {
      wx.navigateTo({
        url: `/mall/logistics/logistics?id=${this.data.id}&orderId=${order.id}`,
      })
      return
    }

    const info = JSON.stringify(e.currentTarget.dataset.logistics)
    wx.navigateTo({
      url: `/mall/logisticsInfo/logisticsInfo?id=${this.data.id}&info=${info}`,
    })
  },
  onPageScroll(e) {
    if (e.scrollTop > GlobalData.clientHeihgt / 4) {
      this.setData({
        scrollTop: true,
      })
    } else {
      this.setData({
        scrollTop: false,
      })
    }
  },
  /**
   * 填写发货
   * @param e 目标控件事件
   * @returns 不返回
   */
  writeShip(e: WechatMiniprogram.CustomEvent) {
    let orderId = +e.currentTarget.dataset.id
    const { orderInfo } = this.data
    this.setData({ orderIds: [] }) // 防止上次选择的数据干扰
    // 可以选择发货的数量
    let canWritShipNum = 0
    if (orderInfo.parentOrder) {
      // 聚合订单。存在多个未发货订单则显示弹窗。只有一个未发货则直接进入发货页面
      orderId = 0
      for (const order of orderInfo.sub_orders) {
        if (['PS_SUCCEEDED', 'RF_REFUSE'].includes(order.status)) {
          canWritShipNum += 1
          orderId = order.id
        }
      }
    }
    console.log('==> ', orderId)
    if (canWritShipNum > 1) {
      // 有多个需要发货的才显示弹窗
      this.setData({ show: true, boxType: 'ship' })
    } else if (canWritShipNum == 1) {
      // 子订单中只有一个需要发货
      GlobalData.shipInfo.orderIds = [orderId]
      wx.navigateTo({ url: `/mall/fillShipInfo/fillShipInfo` })
    } else {
      // 只有一个订单的情况
      GlobalData.shipInfo.orderId = orderId
      wx.navigateTo({ url: `/mall/fillShipInfo/fillShipInfo` })
    }
  },
  goUser(event: any) {
    wx.navigateTo({
      url: `/mine/homePage/homePage?id=${event.currentTarget.dataset.id}`,
    })
  },
  toDetail(event: WechatMiniprogram.BaseEvent) {
    const data = event.currentTarget.dataset as { id: number; orderId: number }
    wx.navigateTo({ url: `/mall/detail/detail?commodityId=${data.id}&orderId=${data.orderId}` })
  },
  /**
   * 复制订单
   */
  copyOrder() {
    // 复制订单号
    wx.setClipboardData({
      data: this.data.orderInfo.trade_no,
      success: () => {
        wx.showToast({
          title: '订单号复制成功',
          icon: 'none',
          duration: 2000,
        })
      },
      fail: () => {
        wx.showToast({
          title: '订单号复制失败',
          icon: 'none',
          duration: 2000,
        })
      },
    })
  },
  toSnapshot() {
    const { id, commodity_id, parentOrder } = this.data.orderInfo
    if (parentOrder) {
      wx.navigateTo({ url: `/mall/snapshot/index` })
    } else {
      wx.navigateTo({
        url: `/mall/snapshot/detail/detail?commodityId=${commodity_id}&orderId=${id}`,
      })
    }
  },
  showConfirm() {
    this.setData({ show: true })
  },
  close() {
    this.setData({ show: false, orderIds: [] })
  },
  checkBoxChange(e: any) {
    console.log(e)
    const { value } = e.detail
    this.setData({ orderIds: value.map((val: string) => +val) })
  },
  comfrim() {
    const { orderInfo } = this.data
    let orderId = 0
    this.setData({ orderIds: [] }) // 防止上次选择的数据干扰
    if (orderInfo.parentOrder) {
      // 聚合订单。存在多个待收货订单则显示弹窗。只有一个待收货则直接进入发货页面
      for (const group of orderInfo.sub_orders) {
        for (const order of group) {
          if (['EP_SEND', 'RT_AGREE'].includes(order.status)) {
            // 再次发现待收货订单。打开选择弹窗
            if (orderId) {
              this.setData({ show: true })
              return
            }
            orderId = order.id
          }
        }
      }
      this.setData({ orderIds: [orderId] })
    }

    $event.emit('showSheet', [
      {
        title: `是否确认收货？`,
        desc: `为保证你的售后权益，请收到商品确认无误\n后再确认收货`,
        enableBottom: true,
        fontWeight: true,
      },
      {
        title: `确认收货`,
        method: this.confirmOrder,
      },
    ])
  },
  async confirmOrder() {
    const { orderId, orderIds } = this.data
    const ids = orderIds.length ? orderIds : [orderId]
    try {
      await Promise.all(ids.map((id) => mallApi.confirmOrder(id)))
      wx.showToast({
        title: '确认收货',
      })
      this.setData({
        [`orderInfo.receipt_at`]: 1,
      })
      $event.emit('mallOrderChange')
      $event.emit('after:confirm', orderId)
    } catch (error) {
      wx.showToast({
        title: `${getMessage(error.data).getMessage() || '操作失败'}`,
        icon: 'none',
      })
    }
  },
  boxConfirm(e: any) {
    if (this.data.boxType === 'ship') {
      GlobalData.shipInfo.orderIds = this.data.orderIds
      wx.navigateTo({ url: `/mall/fillShipInfo/fillShipInfo` })
    } else {
      $event.emit('showSheet', [
        {
          title: `是否确认收货？`,
          desc: `为保证你的售后权益，请收到商品确认无误\n后再确认收货`,
          enableBottom: true,
          fontWeight: true,
        },
        {
          title: `确认收货`,
          method: this.confirmOrder,
        },
      ])
    }
    this.setData({ show: false })
  },
  comment() {
    const {
      data: {
        orderInfo: { commodity_id: id },
      },
    } = this
    this.setData({
      mall_commodities: this.data.orderInfo.commodity,
    })
    wx.showActionSheet({
      itemList: ['文字', '图片', '视频'],
      success(res) {
        switch (res.tapIndex) {
          case 0:
            wx.navigateTo({
              url: `/pages/publish/publish?about=mall_commodities&id=${id}`,
            })
            break

          case 1:
            wx.navigateTo({
              url: `/pages/publish/publish?type=image&about=mall_commodities&id=${id}`,
            })
            break
          case 2:
            wx.navigateTo({
              url: `/pages/publish/publish?type=video&about=mall_commodities&id=${id}`,
            })
            break
        }
      },
    })
  },
  /** 修改地址 */
  changeAddress() {
    const {
      data: {
        orderInfo: { id },
        index,
      },
    } = this
    wx.chooseAddress({
      success: (res) => {
        const form = {
          name: res.userName,
          phone: res.telNumber,
          province: res.provinceName,
          city: res.cityName,
          country: res.countyName,
          detail: res.detailInfo,
        }
        mallApi
          .editOrder(id, {
            address: form,
          })
          .then(() => {
            this.setData({
              ['orderInfo.address']: form,
            })
            const pages = getCurrentPages()
            const lastPage = pages[pages.length - 2]
            lastPage.setData({
              [`list[${index}].address`]: form,
            })
            wx.showToast({
              title: '修改成功',
            })
          })
          .catch(() => {
            wx.showToast({
              title: '修改失败',
              icon: 'none',
            })
          })
      },
    })
  },
  /** 取消订单 */
  cancelOrder() {
    const {
      data: {
        orderInfo: { id },
        index,
      },
    } = this
    mallApi
      .cancelOrder(id)
      .then(() => {
        this.setData({
          ['orderInfo.pay_status']: 4,
        })
        const pages = getCurrentPages()
        const lastPage = pages[pages.length - 2]
        lastPage.setData({
          [`list[${index}].pay_status`]: 4,
        })
        wx.showToast({
          title: '订单已取消',
          icon: 'none',
        })
      })
      .catch(() => {
        wx.showToast({
          title: '取消失败',
          icon: 'none',
        })
      })
  },
  pay() {
    const {
      data: {
        orderInfo: { id },
        index,
      },
    } = this
    mallApi
      .payAgin(id, {
        openid: wx.getStorageSync(`${getServer()}/openId`).data,
        appid: getAppId() ? getAppId() : '{{APP_ID}}',
        pay_method: 'WechatPay_Js',
      })
      .then((res) => {
        if (res.pay_amount == 0) {
          return this.paySucess(index)
        }
        wx.requestPayment({
          ...res.pay_data,
          success: () => {
            this.paySucess(index)
          },
          fail: () => {
            wx.showToast({
              title: '支付失败',
              icon: 'none',
            })
          },
        })
      })
      .catch(() => {
        wx.showToast({
          title: '支付失败',
          icon: 'none',
        })
      })
  },
  paySucess(index: number) {
    this.setData({
      ['orderInfo.pay_status']: 1,
    })
    const pages = getCurrentPages()
    const lastPage = pages[pages.length - 2]
    lastPage.setData({
      [`list[${index}].pay_status`]: 1,
    })
    wx.showToast({
      title: '支付成功',
    })
  },
  async optionHandle(e: any) {
    const { type, order, disable } = e.currentTarget.dataset
    this.setData({ orderInfoTemp: order || this.data.orderInfo })
    const { orderInfoTemp, orderId, index } = this.data
    switch (type) {
      case 'contact':
        wx.navigateTo({
          url: `/mall/form/index?type=appeal&orderId=${orderInfoTemp.id}&disable=${disable}`,
        })
        break
      case 'del':
        $event.emit('showSheet', [
          {
            title: `是否删除订单`,
            desc: '订单删除后，相关购买记录将无法恢复',
            enableBottom: true,
            fontWeight: true,
          },
          {
            title: `删除`,
            method: () => {
              mallApi
                .resetMallOrder(
                  orderId,
                  this.data.id === 5 ? { user_deleted: true } : { shop_deleted: true },
                )
                .then(() => {
                  const pages = getCurrentPages()
                  const lastpage = pages[pages.length - 2]
                  const list = lastpage.data.list
                  list.splice(index, 1)
                  lastpage.setData({ list })
                  wx.showToast({ title: '删除成功' })
                  setTimeout(() => {
                    wx.navigateBack({ delta: 1 })
                  }, 1000)
                })
                .catch((error) => {
                  wx.showToast({
                    title: `${getMessage(error.data).getMessage()}`,
                    icon: 'none',
                  })
                })
            },
          },
        ])
        break
    }
  },
  // 退款/退货/协商/申诉页面跳转
  async toForm(e: any) {
    const { type, order } = e.currentTarget.dataset
    this.setData({ orderInfoTemp: order || this.data.orderInfo })
    const { orderInfoTemp } = this.data
    await getUser()
    const text = type === 'refund' ? '退款' : type === 'return' ? '退货' : '协商退款'
    if (orderInfoTemp.refund_count >= GlobalData.mall.refund_count) {
      wx.showToast({
        title: '申请次数已用完',
        icon: 'error',
      })
      return
    }

    let desc = ''
    if (orderInfoTemp.refund_count === 0) {
      // 第一次机会
      desc = `买家退货、退款、协商退款申请被驳回后可再次申请，共有${GlobalData.mall.refund_count}次机会。若买家在申请审核的过程中取消申请，也会计入申请次数`
    } else if (GlobalData.mall.refund_count - GlobalData.mall.refund_count === 1) {
      // 最后一次
      desc = `你共有${GlobalData.mall.refund_count}次申请退款、退货、协商退款的机会，这是你第${
        orderInfoTemp.refund_count + 1
      }次申请，申请被驳回后，你将不能再提交`
    } else {
      // 中间的
      desc = `你共有${GlobalData.mall.refund_count}次申请退款、退货、协商退款的机会，这是你第${
        orderInfoTemp.refund_count + 1
      }次申请， 是否继续申请？`
    }

    $event.emit('showSheet', [
      {
        title: `${text}提示`,
        desc,
        enableBottom: true,
        fontWeight: true,
      },
      {
        title: `申请${text}`,
        url: `/mall/form/index?type=${type}&orderId=${orderInfoTemp.id}&retId=${
          orderInfoTemp.refund ? orderInfoTemp.refund.id : ''
        }&shopkeeper=${this.data.isSaleOrder ? '1' : ''}`,
      },
    ])
  },
  // 退款/退货/协商/申诉详情页面跳转
  toFormInfo(e: any) {
    const { type, order } = e.currentTarget.dataset
    this.setData({ orderInfoTemp: order || this.data.orderInfo })
    const { orderInfoTemp } = this.data
    wx.navigateTo({
      url: `/mall/formInfo/index?type=${type}&orderId=${orderInfoTemp.id}&retId=${
        orderInfoTemp.refund ? orderInfoTemp.refund.id : ''
      }&shopkeeper=${this.data.isSaleOrder ? '1' : ''}`,
    })
  },
  /**
   * 冻结状态：0-正常，1-冻结中（申诉中），2-冻结中（后台受理申诉），3-处理中（后台处理申诉），4-已关闭（申诉完成，已关闭），5-被驳回（后台驳回申诉）
   * 按照excel订单状态判断：https://docs.qq.com/sheet/DUGlZTFlDQ25qRXdK
   * 状态：
   *     先判断冻结字段，再判断status的状态
   *     如果是已冻结、冻结被驳回、冻结已受理，就直接显示冻结情况
   *     如果是处理中，显示“申诉已处理+status的状态”
   *     如果是已关闭，显示“status的状态”
   */
  orderStatusResolve(orderInfo: any, shopkeeper?: boolean) {
    const maxRefundCount = GlobalData.mall.refund_count
    const { refund_count = 0, locked = 0, status } = orderInfo // refund_count:已使用次数
    let icon = '' // 状态图标
    let title = '' // 状态文本
    let text = '' // 提示内容

    // 公共按钮：付款、修改地址、取消、确认收货、删除
    // 以下为单个订单的按钮显示控制
    let isAppeal = false // 是否可以申诉
    let isRefund = false // 是否可以申请退款
    let isReturn = false // 是否可以申请退货
    let isNegotiate = false // 是否可以申请协商退款
    let isComment = false // 是否可以评价
    let showRefund = false // 是否可以查看退款
    let showReturn = false // 是否可以查看退货
    let showNegotiate = false // 是否可以查看协商
    let writeShip = false // 填写发货

    // 正常订单的状态判断
    const statusResolve = () => {
      switch (status) {
        case 'PS_UNPAID':
          title = '待付款'
          icon = 'status2'
          break
        case 'PS_SUCCEEDED':
          title = shopkeeper ? '已付款' : '等待发货'
          icon = shopkeeper ? 'status2' : 'status7'
          text = shopkeeper ? '买家已付款，等待核验' : '买家已付款，等待核验'
          isAppeal = true
          if (shopkeeper) {
            writeShip = true
          } else {
            isRefund = refund_count < maxRefundCount
          }
          break
        case 'PS_EXPIRED':
          title = '支付超时'
          icon = 'status10'
          break
        case 'PS_CANCEL':
          title = '订单已取消'
          icon = 'status0'
          break
        case 'EP_SEND':
          title = '已发货'
          icon = 'status5'
          text = this.getRemainDeliveryTime(orderInfo, shopkeeper)
          isAppeal = true
          isReturn = refund_count < maxRefundCount && !shopkeeper
          break
        case 'EP_SIGNED':
          title = '已收货'
          icon = 'status7'
          text = shopkeeper ? '买家已收货，等待买家评价' : '货物已收到，记得去评价哦'
          isComment = !shopkeeper
          break
        case 'EP_TIMEOUT':
          title = '签收超时已收货'
          icon = 'status7'
          text = shopkeeper ? '买家已收货，等待买家评价' : '已经超过最长收货时间，已自动收货'
          isComment = !shopkeeper
          break
        case 'RF_APPLY':
          title = '申请退款中'
          icon = 'status3'
          text = shopkeeper ? '买家已申请退款，快快处理哦' : '退款申请已提交，等待商家同意退款'
          isAppeal = true
          showRefund = true // 商家显示: 处理退款
          break
        case 'RF_AGREE':
          title = '同意退款'
          icon = 'status1'
          text = shopkeeper ? '' : '商家已同意退款，等待平台返回交易金额'
          isAppeal = true
          showRefund = true
          break
        case 'RF_REFUSE':
          title = shopkeeper ? '驳回退款申请' : '退款申请被驳回'
          icon = 'status0'
          text = shopkeeper
            ? ''
            : refund_count < maxRefundCount
            ? `商家驳回了你的退款申请，你还有${maxRefundCount - refund_count}次申请退款机会`
            : `商家驳回了你的退款申请，${refund_count}次退款机会已用完，如有疑问，可联系平台`
          isAppeal = true
          showRefund = true
          isRefund = refund_count < maxRefundCount && !shopkeeper
          break
        case 'RF_FINISH':
          title = '退款成功'
          icon = 'status1'
          showRefund = true
          break
        case 'RF_OTHER':
          title = '三方退款成功'
          icon = 'status1'
          text = shopkeeper
            ? ''
            : `退回金额${(orderInfo.refund.pay_amount / 100).toFixed(2)}元，${
                orderInfo.refund.pay_score
              }${this.data.currencyName}待入账`
          isAppeal = true
          showRefund = true
          break
        case 'RF_FAILED':
          title = '退款失败'
          icon = 'status0'
          text = '如有疑问，请联系平台'
          isAppeal = true
          showRefund = true
          break
        case 'RT_APPLY':
          title = '申请退货中'
          icon = 'status6'
          text = shopkeeper ? '买家已申请退货，快快处理哦' : '退货申请已提交，等待商家同意退货'
          isAppeal = true
          showReturn = true // 商家显示: 处理退货
          break
        case 'RT_REFUND':
          title = '已拦截发货直接退款'
          icon = 'status3'
          text = shopkeeper ? '' : '商家已拦截发货，等待平台返回交易金额'
          isAppeal = true
          showReturn = true
          break
        case 'RT_AGREE':
          title = shopkeeper ? '等待发货' : '商家同意退货'
          icon = shopkeeper ? 'status7' : 'status6'
          text = shopkeeper
            ? '已同意退货申请，等待买家发货'
            : '商家已同意退货申请，请尽快发货并填写发货订单'
          isAppeal = true
          showReturn = true
          break
        case 'RT_REFUSE':
          title = shopkeeper ? '驳回退货申请' : '退货申请被驳回'
          icon = 'status0'
          text = shopkeeper
            ? ''
            : refund_count < maxRefundCount
            ? `商家驳回了你的退货申请，你还有${maxRefundCount - refund_count}次申请退货的机会`
            : `商家驳回了你的退货申请，${maxRefundCount}次退货机会已用完，如有疑问，可联系平台`
          isAppeal = true
          showReturn = true
          isReturn = refund_count < maxRefundCount && !shopkeeper
          break
        case 'RT_SENDOUT':
          title = shopkeeper ? '确认收货' : '已发货'
          icon = 'status5'
          text = this.getRemainDeliveryTimeForShopper(orderInfo, shopkeeper)
          isAppeal = true
          showReturn = true
          break
        case 'RT_TIMEOUT':
          title = '已冻结'
          icon = 'status8'
          text = shopkeeper ? '买家超时发货，订单已冻结' : '超时发货，订单已冻结'
          showReturn = true
          break
        case 'RT_CONFRIM_REFUND':
          title = '已收货'
          icon = 'status7'
          text = shopkeeper ? '' : '商家已收货，等待平台返回交易金额'
          isAppeal = true
          showReturn = true
          break
        case 'RT_OTHER':
          title = '三方退款成功'
          icon = 'status1'
          text = shopkeeper
            ? ''
            : `退回金额${(orderInfo.refund.pay_amount / 100).toFixed(2)}元，${
                orderInfo.refund.pay_score
              }${this.data.currencyName}待入账`
          isAppeal = true
          showReturn = true
          break
        case 'RT_FINISH':
          title = '退款成功'
          icon = 'status1'
          isAppeal = true
          showReturn = true
          break
        case 'RT_FAILED':
          title = '退款失败'
          icon = 'status0'
          text = shopkeeper ? '' : '如有疑问，请联系平台'
          isAppeal = true
          showReturn = true
          break
        case 'RT_CONFRIM_TIMEOUT':
          title = shopkeeper ? '签收超时已收货' : '已收货'
          icon = 'status7'
          text = shopkeeper ? '已经超过最长收货时间，已自动收货' : ''
          showReturn = true
          break
        case 'RT_CONFRIM_NEGOTIATE':
          title = '协商退款'
          icon = 'status3'
          text = this.getNegotiateRemainDeliveryTime(orderInfo, shopkeeper)
          isAppeal = true
          showReturn = true
          isNegotiate = refund_count < maxRefundCount && !shopkeeper
          break
        case 'RT_NEGO_APPLY':
          title = '协商退款申请中'
          icon = 'status3'
          text = shopkeeper ? '买家已提交协商退款，尽快处理哦' : '协商退款申请已提交，等待商家处理'
          isAppeal = true
          showNegotiate = true
          break
        case 'RT_NEGO_AGREE':
          title = shopkeeper ? '同意协商退款' : '商家已同意协商退款'
          icon = 'status1'
          text = shopkeeper ? '' : '等待平台返回协商退款金额'
          isAppeal = true
          showNegotiate = true
          break
        case 'RT_NEGO_REFUSE':
          title = shopkeeper ? '驳回协商退款申请' : '协商退款申请被驳回'
          icon = 'status0'
          text = shopkeeper
            ? ''
            : refund_count < maxRefundCount
            ? `商家驳回了你的协商退款申请，你还有${
                maxRefundCount - refund_count
              }次申请协商退款的机会`
            : `商家驳回了你的协商退款申请，${maxRefundCount}次协商退款机会已用完，如有疑问，可联系平台`
          isAppeal = true
          showNegotiate = true
          isNegotiate = refund_count < maxRefundCount && !shopkeeper
          break
        case 'RT_NEGO_FINISH':
          title = '退款成功'
          icon = 'status1'
          isAppeal = true
          showNegotiate = true
          break
        case 'RT_NEGO_OTHER':
          title = '三方退款成功'
          icon = 'status1'
          text = shopkeeper
            ? ''
            : `退回金额${(orderInfo.refund.pay_amount / 100).toFixed(2)}元，${
                orderInfo.refund.pay_score
              }${this.data.currencyName}待入账`
          isAppeal = true
          showNegotiate = true
          break
        case 'RT_NEGO_FAILED':
          title = '退款失败'
          icon = 'status0'
          text = shopkeeper ? '' : '如有疑问，请联系平台'
          isAppeal = true
          showNegotiate = true
          break
        case 'CLOSE':
          title = '已关闭'
          icon = 'status0'
          break
        case 'COMMENTED':
          title = '已评价'
          icon = 'status1'
          break
      }
    }
    statusResolve()

    // 冻结订单
    switch (locked) {
      case 1: // 已冻结
        title = '已冻结'
        icon = 'status8'
        text = '平台已收到反馈，即将介入处理'
        isAppeal = false
        isRefund = false
        isReturn = false
        isNegotiate = false
        writeShip = false
        showRefund = false
        showReturn = false
        showNegotiate = false
        break
      case 2: // 冻结已受理
        title = '申诉已受理'
        icon = 'status4'
        text = '平台介入处理，请耐心等待'
        isAppeal = false
        isRefund = false
        isReturn = false
        isNegotiate = false
        writeShip = false
        showRefund = false
        showReturn = false
        showNegotiate = false
        break
      case 3: // 处理中。用户可操作
        text = '申诉已处理，' + text
        break
      case 5: // 驳回。用户可操作
        icon = 'status0'
        title = '申诉被驳回'
        text = '平台驳回了申诉，点击查看详情'
        isAppeal = true
        break
    }
    // 移除多余逗号
    text.length && text.charAt(text.length - 1) === '，' && (text = text.substr(0, text.length - 1))

    return {
      icon,
      title,
      text,
      isAppeal,
      isRefund,
      isReturn,
      isNegotiate,
      isComment,
      showRefund,
      showReturn,
      showNegotiate,
      writeShip,
    }
  },
  /**
   * 假设自动收货时间为4天
   *   3月3日全天发货的订单，都在 3+4 = 7号凌晨的某一个时间点统一结算为“自动收货”。
   *（页面按自动收货的日期显示）
   *    商家已发货，3月7日自动确认收货
   * @param orderInfo 订单信息
   * @param shopkeeper  是否是商家从销售订单进入
   */
  getRemainDeliveryTime(orderInfo: any, shopkeeper?: boolean) {
    const cptTime = this.getTime(
      orderInfo.express_at,
      +GlobalData.mall.default_confirm_receipt * 3600 * 24_000,
    )
    return shopkeeper
      ? `等待买家确认收货，${cptTime}自动确认收货`
      : `商家已发货，${cptTime}自动确认收货`
  },
  /**
   * 买家退货，已发货，商家剩余自动确认收货时间
   * @param orderInfo 订单信息
   * @param shopkeeper  是否是商家从销售订单进入
   */
  getRemainDeliveryTimeForShopper(orderInfo: any, shopkeeper?: boolean) {
    const cptTime = this.getTime(
      orderInfo.refund.express_at,
      +GlobalData.mall.refund_deliver_time * 3600 * 24_000,
    )
    return shopkeeper
      ? `买家已发货，${cptTime}自动确认收货`
      : `等待商家收货，${cptTime}自动确认收货`
  },
  getNegotiateRemainDeliveryTime(orderInfo: any, shopkeeper?: boolean) {
    const cptTime = this.getTime(
      orderInfo.refund.receipt_at,
      (shopkeeper
        ? +GlobalData.mall.refund_deliver_time
        : +GlobalData.mall.refund_negotiate_user_time) *
        3600 *
        24_000,
    )
    return shopkeeper
      ? `请与买家协商具体退款金额，截止${cptTime}`
      : `请与商家协商退款金额，并重新申请退款，截止${cptTime}`
  },
  /** 获取小时分钟 */
  getTime(time: any, delay = 0) {
    let date
    if (typeof time === 'string' && /\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}/.test(time)) {
      time = time.replace(/-/g, '/')
      date = new Date(time)
      const offset = new Date().getTimezoneOffset() * 60 * 1000
      date = new Date(+date - offset)
    } else {
      date = new Date(time as number)
    }

    date = new Date(date.getTime() + delay)
    return `${date.getMonth() + 1}月${date.getDate()}日`
  },
})
